package cn.tedu.egmvc6.controller;

import cn.tedu.egmvc6.base.response.JsonResult;
import cn.tedu.egmvc6.base.response.StateCode;
import cn.tedu.egmvc6.mapper.UserMapper;
import cn.tedu.egmvc6.pojo.dto.UserLoginParam;
import cn.tedu.egmvc6.pojo.dto.UserRegParam;
import cn.tedu.egmvc6.pojo.entity.User;
import cn.tedu.egmvc6.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@Slf4j
@Api(tags = "01.用户管理")
@RequestMapping("/v1/users/")
public class UserController {
    //用户注册的功能
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("用户注册")
    @ApiOperationSupport(order = 10)
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserRegParam userRegParam){
        String username = userRegParam.getUsername();
        UserVO  userVO=userMapper.selectByUsername(username);
        if (userVO!=null){
            return new JsonResult(StateCode.USERNAME_EXIST);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        userMapper.reg(user);
        return JsonResult.ok();
    }
    //登录功能
    @ApiOperation("用户登录")
    @ApiOperationSupport(order = 20)
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        String username = userLoginParam.getUsername();
        String password = userLoginParam.getPassword();
        UserVO userVO = userMapper.login(username,password);
        if (userVO!=null){
            session.setAttribute("user",userVO);
            return JsonResult.ok(userVO);
        }
        return new JsonResult(StateCode.USERNAME_PASSWORD_ERROR);
    }
    //查看当前用户
    @ApiOperation("当前用户")
    @ApiOperationSupport(order = 30)
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVO userVO=(UserVO )session.getAttribute("user");
        if (userVO ==null){
            return new JsonResult(StateCode.NOT_LOGIN);
        }
        return JsonResult.ok(userVO);
    }
    //退出登录
    @ApiOperation("退出登录")
    @ApiOperationSupport(order = 40)
    @GetMapping("logout")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.ok();
    }
}
